import { BASEURL } from './config'
const app = getApp()

const defaultOptions = {
  data: {},
  ignoreToken: false,
  form: false,
}

/**
 * 发送请求
 * @params
 * method: <String> 请求方式: POST/GET
 * url: <String> 请求路径
 * data: <Object> 请求参数
 * ignoreToken: <Boolean> 是否忽略token验证
 * form: <Boolean> 是否使用formData请求
 */
async function request (options) {
  let _options = Object.assign(defaultOptions, options)
  let { method, url, data, ignoreToken, form } = _options
  // 设置请求头
  let header = {}
  if (form) {
    header = {
      'content-type': 'application/x-www-form-urlencoded'
    }
  } else {
    header = {
      'content-type': 'application/json' //自定义请求头信息
    }
  }
  if (!ignoreToken) {
    // 从全局变量中获取token
    let token = app.globalData.token
    if (!token) {
      // 从数据缓存中获取token
      token = wx.getStorageSync('token')
      if (token) {
        app.globalData.token = token
      } 
      else {
        try {
          const code = await login()
          token = await getToken(code)
        } catch(e) {
          wx.showModal({
            title: '错误提示',
            content: e,
            success (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          return Promise.reject(e)
        }
      }
    }
    header.auth = `${token}`
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASEURL + url,
      data,
      header,
      method,
      success: (res) => {
        if(res.data.errno === 1) {
          wx.showModal({
            title: '错误提示',
            content: res.data.msg,
            success (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          reject(res.data.msg)        
        }
        resolve(res.data)
      },
      fail: (err) => {
        wx.showModal({
          title: '错误提示',
          content: err,
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        reject(err)
      }
    })
  })
}

function login() {
  // 登录
  return new Promise((resolve, reject) => {
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        resolve(res.code)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

function getToken(code) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: 'http://192.168.1.8:5000/wechat_login',
      method: 'post',
      data: {
        code: code
      },
      success: res => {
        if(res.data.errno === 0) {
          app.globalData.token = res.data.data
          wx.setStorage({ key: 'token', data: res.data.data })
          resolve(res.data.data)
        } else {
          reject(res.data.msg)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

function get (options) {
  return request({
    method: 'GET',
    ...options
  })
}

function post (options) {
  // url, data = {}, ignoreToken, form
  return request({
    method: 'POST',
    ...options
  })
}

export {
  get,
  post
}